package com.cskaoyan.service;

import com.cskaoyan.bean.BO.CheckoutBO;
import com.cskaoyan.bean.BO.WxCartCheckedBO;
import com.cskaoyan.bean.PO.*;
import com.cskaoyan.bean.VO.CartTotalVO;
import com.cskaoyan.bean.VO.MarketGoodsVo;
import com.cskaoyan.bean.VO.WxCartCheckoutVO;
import com.cskaoyan.bean.VO.WxCartIndexVO;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.MyGetCurrentTime;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.events.Event;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName WxCartServiceImpl
 * @Description
 * @Author Lxz
 * @Date 2022-8-17 9:06
 */
@Service
public class WxCartServiceImpl implements WxCartService {
    @Autowired
    MarketCartMapper cartMapper;
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketGoodsProductMapper goodsProductMapper;
    @Autowired
    MarketOrderMapper orderMapper;
    @Autowired
    MarketAddressMapper addressMapper;
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCouponUserMapper couponUserMapper;

    @Override
    public Integer goodsCount() {
        MarketCartExample example = new MarketCartExample();
        List<MarketCart> marketCarts = cartMapper.selectByExample(example);
        int count = 0;
        for (MarketCart marketCart : marketCarts) {
            count += marketCart.getNumber();
        }
        return count;
    }


    @Override
    public void add(MarketCart marketCart) {
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andGoodsIdEqualTo(marketCart.getGoodsId());
        criteria.andProductIdEqualTo(marketCart.getProductId());
        List<MarketCart> marketCarts = cartMapper.selectByExample(cartExample);
        // 若有 该商品该规格的购物车数据，则 添加其number
        if (marketCarts.size() == 1) {
            Short number = marketCarts.get(0).getNumber();
            short addNumber = (short) (number + marketCart.getNumber());
            marketCart.setNumber(addNumber);
            cartMapper.updateByExampleSelective(marketCart,cartExample);
            return;
        }

        // 若没有 该商品该规格的购物车数据，则 插入数据

        // 通过 goods表 获取goods_sn 、 goods_name
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.createCriteria().andIdEqualTo(marketCart.getGoodsId());
        List<MarketGoodsVo> marketGoodsVos = goodsMapper.selectByExampleVo(goodsExample);
        //  通过 goods_product表 获取 product_id 、 price 、 specifications 、 pic_url
        MarketGoodsProductExample goodsProductExample = new MarketGoodsProductExample();
        goodsProductExample.createCriteria().andIdEqualTo(marketCart.getProductId());


        List<MarketGoodsProduct> marketGoodsProducts = goodsProductMapper.selectByExample(goodsProductExample);


        // userid , checked = false (sql默认1) , addTime 和 UpdateTime 一样 ，deleted不用管 默认0
        Date currentTime = MyGetCurrentTime.getCurrentTime();

        marketCart.setGoodsSn(marketGoodsVos.get(0).getGoodsSn());
        marketCart.setGoodsName(marketGoodsVos.get(0).getName());
        marketCart.setPrice(marketGoodsProducts.get(0).getPrice());

        marketCart.setSpecifications(marketGoodsProducts.get(0).getSpecifications());
        marketCart.setPicUrl(marketGoodsProducts.get(0).getUrl());
        /*
         * todo-Lxz userId 没有测试
         * @Date  14:19
         **/
        marketCart.setUserId(marketCart.getUserId());
        marketCart.setChecked(false);
        marketCart.setAddTime(currentTime);
        marketCart.setUpdateTime(currentTime);

        cartMapper.insertSelective(marketCart);
    }

    @Override
    public WxCartIndexVO index() {
        MarketCartExample example = new MarketCartExample();
        example.createCriteria().andDeletedEqualTo(false);
        List<MarketCart> marketCarts = cartMapper.selectByExample(example);
        WxCartIndexVO wxCartIndexVO = new WxCartIndexVO();
        wxCartIndexVO.setCartList(marketCarts);
        Integer goodsCount = 0;
        Integer checkedGoodsCount = 0;
        Double goodsAmount = 0.0;
        Double checkedGoodsAmount = 0.0;
        for (MarketCart marketCart : marketCarts) {
            Short number = marketCart.getNumber();
            Double price = marketCart.getPrice().doubleValue();
            Double amount = price * number;
            goodsCount += number;
            goodsAmount += amount;
            if (marketCart.getChecked()) {
                checkedGoodsCount += number;
                checkedGoodsAmount += amount;
            }
        }
        CartTotalVO cartTotalVO = new CartTotalVO(goodsCount, checkedGoodsCount, goodsAmount, checkedGoodsAmount);
        wxCartIndexVO.setCartTotal(cartTotalVO);
        return wxCartIndexVO;
    }

    /*
     * todo-Lxz 检查所有 update 和 delete 有无加上updatetime
     * @Date  12:29
     **/
    @Override
    public void update(MarketCart marketCart) {
        Date currentTime = MyGetCurrentTime.getCurrentTime();
        marketCart.setUpdateTime(currentTime);
        cartMapper.updateByPrimaryKeySelective(marketCart);
    }

    @Override
    public void delete(WxCartCheckedBO wxCartCheckedBO) {
        Integer[] productIds = wxCartCheckedBO.getProductIds();
        MarketCart marketCart = new MarketCart();
        marketCart.setDeleted(true);
        marketCart.setUpdateTime(MyGetCurrentTime.getCurrentTime());
        for (Integer productId : productIds) {
            MarketCartExample example = new MarketCartExample();
            example.createCriteria().andProductIdEqualTo(productId);
            cartMapper.updateByExampleSelective(marketCart, example);
        }
    }

    /*
     * todo-Lxz 若有 该商品该规格的购物车数据，则 立即购买选定数量，
     *               但是不付款的话 ，就会将原有购物车中数量改变为 立即购买的数量
     *               看下能不能通过 订单状态控制
     * @Date  16:23
     **/
    @Override
    public void fastadd(MarketCart marketCart) {

        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andGoodsIdEqualTo(marketCart.getGoodsId());
        criteria.andProductIdEqualTo(marketCart.getProductId());
        List<MarketCart> marketCarts = cartMapper.selectByExample(cartExample);
        // 若有 该商品该规格的购物车数据，则 立即购买选定数量
        if (marketCarts.size() == 1) {
            marketCart.setNumber(marketCart.getNumber());
            cartMapper.updateByExampleSelective(marketCart,cartExample);
            return;
        }

        // 通过 goods表 获取goods_sn 、 goods_name
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.createCriteria().andIdEqualTo(marketCart.getGoodsId());
        List<MarketGoodsVo> marketGoodsVos = goodsMapper.selectByExampleVo(goodsExample);
        //  通过 goods_product表 获取 product_id 、 price 、 specifications 、 pic_url
        MarketGoodsProductExample goodsProductExample = new MarketGoodsProductExample();
        goodsProductExample.createCriteria().andIdEqualTo(marketCart.getProductId());


        List<MarketGoodsProduct> marketGoodsProducts = goodsProductMapper.selectByExample(goodsProductExample);


        // userid , addTime 和 UpdateTime 一样 ，deleted不用管 默认0
        // checked = true 不然checkout里面没有
        Date currentTime = MyGetCurrentTime.getCurrentTime();

        marketCart.setGoodsSn(marketGoodsVos.get(0).getGoodsSn());
        marketCart.setGoodsName(marketGoodsVos.get(0).getName());
        marketCart.setPrice(marketGoodsProducts.get(0).getPrice());

        marketCart.setSpecifications(marketGoodsProducts.get(0).getSpecifications());
        marketCart.setPicUrl(marketGoodsProducts.get(0).getUrl());
        /*
         * todo-Lxz userId 没有测试
         * @Date  14:19
         **/
        marketCart.setUserId(marketCart.getUserId());
        marketCart.setChecked(true);
        marketCart.setAddTime(currentTime);
        marketCart.setUpdateTime(currentTime);

        cartMapper.insertSelective(marketCart);

    }


    @Override
    public void checked(WxCartCheckedBO wxCartCheckedBO) {
        Integer[] productIds = wxCartCheckedBO.getProductIds();
        MarketCart marketCart = new MarketCart();
        if (wxCartCheckedBO.getIsChecked() == 1) {
            marketCart.setChecked(true);
        } else {
            marketCart.setChecked(false);
        }
        for (Integer productId : productIds) {
            MarketCartExample example = new MarketCartExample();
            example.createCriteria().andProductIdEqualTo(productId);
            cartMapper.updateByExampleSelective(marketCart, example);
        }
    }


    @Override
    public WxCartCheckoutVO checkout(CheckoutBO checkoutBO) {

        // 通过 cartId 在 cart表中 查找 actualPrice ，以及checkedGoodsList
        Double actualPrice = 0.0;
        Double freightPrice = 0.0;
        // cartId = 0 --》 找checked=1的数据
        // cartId 为确定值 则找该单值
        Integer cartId = checkoutBO.getCartId();
        ArrayList<MarketCart> marketCarts = new ArrayList<>();

       // Session session = SecurityUtils.getSubject().getSession();
       // Integer[] ids = null;

        if (cartId == 0) {
            MarketCartExample example = new MarketCartExample();
            List<MarketCart> marketCartsAll = cartMapper.selectByExample(example);

            for (MarketCart marketCart : marketCartsAll) {
                int i = 0;
                if (marketCart.getChecked()) {

                   // ids[i] = marketCart.getId();
                   // i++;

                    Short number = marketCart.getNumber();
                    double price = marketCart.getPrice().doubleValue();
                    Double amount = number * price;
                    actualPrice += amount;
                    marketCarts.add(marketCart);
                }
            }
           // session.setAttribute("cartIds",ids);
        } else {
           // ids[0] = cartId;
           // session.setAttribute("cartIds",ids);

            MarketCart marketCart = cartMapper.selectByPrimaryKey(cartId);

            cartId = marketCart.getId();

            Short number = marketCart.getNumber();
            double price = marketCart.getPrice().doubleValue();
            actualPrice = number * price;
            marketCarts.add(marketCart);
        }

        Double orderTotalPrice = 0.0;
        Double goodsTotalPrice = 0.0;
        double couponPrice = 0.0;
        int availableCouponLength = 0;
        if (checkoutBO.getCouponId() != 0) {
            // 通过couponId 查询 coupon表的  couponPrice
            MarketCoupon marketCoupon = couponMapper.selectByPrimaryKey(checkoutBO.getCouponId());
            couponPrice = marketCoupon.getDiscount().doubleValue();
            orderTotalPrice = actualPrice - couponPrice;
            goodsTotalPrice = orderTotalPrice;
        }
        if (checkoutBO.getUserCouponId() != 0) {
            // 通过userCouponId 和 couponId 查询 userCoupon
            MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
            couponUserExample.createCriteria().andCouponIdEqualTo(checkoutBO.getCouponId());
            List<MarketCouponUser> marketCouponUsers = couponUserMapper.selectByExample(couponUserExample);
            availableCouponLength = marketCouponUsers.size();
        }




        // 通过addressId 查询 address表 ，得到 checkedAddress
        // addressId = 0 则获取默认地址
        List<MarketAddress> marketAddresses = null;
        MarketAddressExample addressExample = new MarketAddressExample();
        if (checkoutBO.getAddressId() != 0) {
            addressExample.createCriteria().andIdEqualTo(checkoutBO.getAddressId());
            marketAddresses = addressMapper.selectByExample(addressExample);
        } else {
            addressExample.createCriteria().andIsDefaultEqualTo(true);
            marketAddresses = addressMapper.selectByExample(addressExample);
        }


        WxCartCheckoutVO wxCartCheckoutVO = new WxCartCheckoutVO();
        // 两个团购的先不用
        wxCartCheckoutVO.setGrouponRulesId(checkoutBO.getGrouponRulesId());
        wxCartCheckoutVO.setGrouponPrice(0.0);

        // 四个id从请求得到的
        wxCartCheckoutVO.setCartId(cartId);
        wxCartCheckoutVO.setUserCouponId(checkoutBO.getUserCouponId());
        wxCartCheckoutVO.setCouponId(checkoutBO.getCouponId());
        wxCartCheckoutVO.setAddressId(checkoutBO.getAddressId());

        wxCartCheckoutVO.setActualPrice(actualPrice);
        wxCartCheckoutVO.setOrderTotalPrice(orderTotalPrice);
        wxCartCheckoutVO.setGoodsTotalPrice(goodsTotalPrice);
        wxCartCheckoutVO.setCheckedAddress(marketAddresses.get(0));
        wxCartCheckoutVO.setCouponPrice(couponPrice);
        wxCartCheckoutVO.setAvailableCouponLength(availableCouponLength);
        wxCartCheckoutVO.setFreightPrice(freightPrice);
        wxCartCheckoutVO.setCheckedGoodsList(marketCarts);

        return wxCartCheckoutVO;
    }

}

